#
# fusion.http.http_server
#
# Copyright 2007 Helsinki Institute for Information Technology
# and the authors.
#
# Authors: Ken Rimey <rimey@hiit.fi>
#

# Permission is hereby granted, free of charge, to any person
# obtaining a copy of this software and associated documentation files
# (the "Software"), to deal in the Software without restriction,
# including without limitation the rights to use, copy, modify, merge,
# publish, distribute, sublicense, and/or sell copies of the Software,
# and to permit persons to whom the Software is furnished to do so,
# subject to the following conditions:
#
# The above copyright notice and this permission notice shall be
# included in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
# IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
# CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
# SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

'''
Serve HTTP using webpy.
'''

import SocketServer

import web              # http://webpy.org/

from fusion.db.db import DB

def init_http(path, sync_daemon=None):
    web.config.DB = lambda: DB(path)
    web.config.sync_daemon = sync_daemon
    web.webapi.internalerror = web.debugerror
    SocketServer.ThreadingMixIn.daemon_threads = True

def serve_http(urls, host='127.0.0.1', port=8080, fvars=None):
    addr = '%s:%d' % (host, port)
    try:
        _run(addr, urls, fvars)
    except KeyboardInterrupt:
        pass

def _run(ip_addr_port, inp, fvars, *middleware):
    autoreload = web.reloader in middleware
    f = web.webpyfunc(inp, fvars, autoreload)
    f = web.wsgifunc(f, *middleware)
    return web.runsimple(f, web.validip(ip_addr_port))
